const Proxy = require('../proxy')
const moment = require('moment')
const { numberUtil } = require('../util')

const ExecuteRecord = Proxy.ExecuteRecord
const QuoteVolume = Proxy.QuoteVolume

exports.getRecordsByPage = async function (query, paging) {
  // 新创建的在前面
  const opt = {
    skip: paging.start,
    limit: paging.offset,
    sort: '-create_at',
    lean: true
  }
  const queryNew = {}
  if (query.code) {
    queryNew.code = query.code
  }
  if (query.market) {
    queryNew.market = query.market
  }
  if (query.type) {
    queryNew.type = query.type
  }
  if (query.strategy) {
    queryNew.strategy = query.strategy
  }
  if (query.strategy_result) {
    queryNew.strategy_result = query.strategy_result
  }
  if (query.searchText) {
    queryNew.reason = {
      $regex: query.searchText
    }
  }
  if (query.reason) {
    queryNew.$or = [
      { reason: query.reason },
      { lastReason: query.reason }
    ]
  }
  if (query.startTime || query.endTime) {
    queryNew.create_at = {}
  }
  if (query.startTime) {
    queryNew.create_at.$gt = query.startTime
  }
  if (query.endTime) {
    queryNew.create_at.$lt = query.endTime
  }
  if (query.incomeType) {
    queryNew.income_result = {}
    // 盈利
    if (query.incomeType === '1') {
      queryNew.income_result.$gt = 0
    }
    // 亏损
    if (query.incomeType === '2') {
      queryNew.income_result.$lt = 0
    }
  }
  if (query.addPosition) {
    queryNew.add_times = {}
    if (query.addPosition === '1') {
      queryNew.add_times.$gt = 0
    }
    if (query.addPosition === '2') {
      queryNew.add_times.$lt = 1
    }
  }
  if (query.lossMany) {
    queryNew.loss_many = 1
  }
  const data = await Promise.all([
    ExecuteRecord.find(queryNew, opt),
    ExecuteRecord.count(queryNew)
  ])
  return { list: data[0], count: data[1] }
}

exports.getExecuteRecordDetail = async function (query) {
  return ExecuteRecord.findOneById(query._id)
}

exports.deleteExpireExecuteRecord = async function () {
  const endTime = moment().subtract(12, 'months').toDate()
  const list = await ExecuteRecord.find({
    create_at: {
      $lt: endTime
    }
  })
  await ExecuteRecord.batchDeleteByIds(list.map((v) => {
    return v._id
  }))
  const qEndTime = moment().subtract(24, 'months').toDate()
  const qList = await QuoteVolume.find({
    create_at: {
      $lt: qEndTime
    }
  })
  await QuoteVolume.batchDeleteByIds(qList.map((v) => {
    return v._id
  }))
}

exports.deleteExecuteRecords = async function () {
  await ExecuteRecord.delete({})
}

exports.getExecuteRecordsStatistics = async function (query) {
  // 新创建的在前面
  const opt = {
    sort: '-create_at'
  }
  const recordList = await ExecuteRecord.find({
    market: 2,
    type: { $in: ['sell', 'buy'] },
    create_at: {
      $gt: query.startTime
    }
  }, opt)
  const reasonMap = {}
  recordList.forEach((v) => {
    if (v.income_result) {
      if (reasonMap[v.reason]) {
        reasonMap[v.reason].push(v)
      } else {
        reasonMap[v.reason] = [v]
      }
    }
  })
  const result = []
  for (let reason in reasonMap) {
    const list = reasonMap[reason] || []
    const info = {
      name: reason,
      count: list.length,
      sumIncome: 0,
      sumProfit: 0,
      sumProfitRate: 0,
      sumProfitPosition: 0,
      sumLoss: 0,
      sumLossRate: 0,
      sumLossPosition: 0,
      profitCount: 0,
      lossCount: 0
    }
    list.forEach((v) => {
      info.sumIncome += v.income_result
      if (v.income_result > 0) {
        info.sumProfit += v.income_result
        info.sumProfitRate += v.income_rate_result
        info.sumProfitPosition += v.usdt
        info.profitCount++
      } else {
        info.sumLoss += v.income_result
        info.sumLossRate += v.income_rate_result
        info.sumLossPosition += v.usdt
        info.lossCount++
      }
    })
    info.sumProfit = numberUtil.keepTwoDecimals(info.sumProfit)
    info.sumProfitRate = numberUtil.keepTwoDecimals(info.sumProfitRate)
    info.sumProfitPosition = numberUtil.keepTwoDecimals(info.sumProfitPosition)
    info.sumLoss = numberUtil.keepTwoDecimals(info.sumLoss)
    info.sumLossRate = numberUtil.keepTwoDecimals(info.sumLossRate)
    info.sumLossPosition = numberUtil.keepTwoDecimals(info.sumLossPosition)
    result.push(info)
  }
  return {
    count: recordList.length,
    list: result
  }
}

function formatEmaInfoKey (info, key) {
  const data = {}
  const zb = [
    'sg', 'kdjDiff', 'macd', 'ema5', 'ema10', 'ema20', 'realWave', 'maxNetChangeRatio',
    'isMacdIncrease', 'isMacdDecline', 'isKdjIncrease', 'isKdjDecline', 'isDownLikeL',
    'isEm5Increase', 'isEm5Decline', 'isEm10Increase', 'isEm10Decline', 'isEm20Increase', 'isEm20Decline',
    'macddd', 'macdud', 'kdjdd', 'kdjud', 'b510t20KeepDays', 't510b20KeepDays', 'emListText',
    'days5NetChangeRatio', 'days10NetChangeRatio', 'days20NetChangeRatio',
    'days5RealWave', 'days10RealWave', 'days20RealWave',
    'days5MaxWave', 'days10MaxWave', 'days20MaxWave', 'days2RealMaxWave',
    't20b10KeepDays', 't10b20KeepDays', 't20b5KeepDays',
    't5b20KeepDays', 't10b5KeepDays', 't5b10KeepDays',
    'ema5IncreaseDays', 'ema5DeclineDays', 'ema10IncreaseDays',
    'ema10DeclineDays', 'ema20IncreaseDays', 'ema20DeclineDays',
    'isBuffer', 'isReadjust', 'isAllIncrease', 'isAllDecline', 'isLongKong', 'isLongDuo', 'nowRatio5',
    'isCrimp5Line', 'isCrimp10Line', 'isCrimp20Line'
  ]
  zb.forEach((v) => {
    data[`${key}-${v}`] = info[v]
  })
  return data
}

exports.addExecuteRecord = async (config) => {
  const btbItem = config.btbItem
  const minute15EmaInfo = btbItem.minute15EmaInfo || {}
  const hourEmaInfo = btbItem.hourEmaInfo || {}
  const dayEmaInfo = btbItem.dayEmaInfo || {}
  const hour4EmaInfo = btbItem.hour4EmaInfo || {}
  const weekEmaInfo = btbItem.weekEmaInfo || {}
  const flagRes = btbItem.asRes || {}
  const indexFlagInfo = flagRes.indexFlagInfo || {}
  const btbIndexTotalInfo = config.btbIndexTotalInfo || {}
  const oldList = await ExecuteRecord.find({
    market: 2,
    code: config.code
  }, {
    skip: 0,
    limit: 1,
    sort: '-create_at'
  }) || []
  const lastItem = oldList[0] || {}
  await ExecuteRecord.newAndSave({
    code: config.code,
    market: 2,
    type: config.type,
    reason: config.reason || '',
    leverage: config.leverage || 1,
    quantity: config.quantity || 0,
    lastType: lastItem.type || '',
    lastReason: lastItem.reason || '',
    lastId: lastItem._id || '',
    detail: {
      lastType: lastItem.type || '',
      lastReason: lastItem.reason || '',
      lastLeverage: lastItem.leverage || '',
      lastQuantity: lastItem.quantity || '',
      btbPositionConfig: config.btbPositionConfig || '',
      minSg: btbItem.minSg,
      hourSg: hourEmaInfo.sg || 0,
      hour4Sg: hour4EmaInfo.sg || 0,
      daySg: dayEmaInfo.sg || 0,
      proportion: btbItem.proportion,
      tendencyScore: btbItem.tendencyScore,
      resultPosition: config.resultPosition || 0,
      incomeRate: btbItem.incomeRate,
      unrealizedProfit: btbItem.unrealizedProfit,
      // 份额，多单是正，空单是负数
      balance: btbItem.balance,
      close: btbItem.close,
      // 市值，多单是正，空单是负数
      usdt: btbItem.usdt,
      ...btbIndexTotalInfo,
      ...formatEmaInfoKey(minute15EmaInfo, 'minute15EmaInfo'),
      ...formatEmaInfoKey(hourEmaInfo, 'hourEmaInfo'),
      ...formatEmaInfoKey(hour4EmaInfo, 'hour4EmaInfo'),
      ...formatEmaInfoKey(dayEmaInfo, 'dayEmaInfo'),
      ...formatEmaInfoKey(weekEmaInfo, 'weekEmaInfo'),
      ...indexFlagInfo
    }
  })
}

exports.reFormatExecuteRecords = async function () {
  const list = await ExecuteRecord.find({ market: 2 })
  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    const detail = item.detail || {}
    await ExecuteRecord.update({
      _id: item._id
    }, {
      lastType: detail.lastType || '',
      lastReason: detail.lastReason || ''
    })
  }
}

function getCondition (row, detail) {
  let minute15EmaInfo = {}
  let hourEmaInfo = {}
  let hour4EmaInfo = {}
  for (let key in detail) {
    if (key.indexOf('minute15EmaInfo') === 0) {
      minute15EmaInfo[key.split('-')[1]] = detail[key]
    }
    if (key.indexOf('hourEmaInfo') === 0) {
      hourEmaInfo[key.split('-')[1]] = detail[key]
    }
    if (key.indexOf('hour4EmaInfo') === 0) {
      hour4EmaInfo[key.split('-')[1]] = detail[key]
    }
  }
  if (row.type === 'buy') {
    if (
      detail.positionFen < 60 &&
      hour4EmaInfo.nowRatio5 > 0.5 &&
      hour4EmaInfo.isReadjust &&
      (hour4EmaInfo.macd < 0 && hour4EmaInfo.kdjDiff > 0 && hour4EmaInfo.kdjud <= 2)
    ) {
      return true
    }
  }
  return false
}
// 计算条件统计，用于计算需不需要屏蔽一种买入或者卖出
exports.countConditionStatistics = async function (days) {
  // 新创建的在前面
  const opt = {
    skip: 0,
    limit: days,
    sort: '-create_at'
  }
  const list = await ExecuteRecord.find({
    market: 2,
    lastType: { $in: ['sell', 'buy'] }
  }, opt)
  const reasonMap = {}
  for (let i = 0; i < list.length; i++) {
    const v = list[i]
    // 计算盈利
    const detail = v.detail || {}
    if (v.lastId) {
      const lastItem = await ExecuteRecord.findOneById(v.lastId)
      lastItem.detail = lastItem.detail || {}
      if (getCondition(lastItem, lastItem.detail)) {
        v.quantity = v.quantity || 0
        v.incomeRate = detail.incomeRate || 0
        v.unrealizedProfit = detail.unrealizedProfit || 0
        v.balance = detail.balance || 0
        v.usdt = detail.usdt || 0
        v.showIncome = v.unrealizedProfit
        if (v.showIncome && detail.lastReason) {
          if (reasonMap[detail.lastReason]) {
            reasonMap[detail.lastReason].list.push(v)
          } else {
            reasonMap[detail.lastReason] = {
              type: detail.lastType,
              list: [v]
            }
          }
        }
      }
    }
  }
  const result = {}
  for (let reason in reasonMap) {
    const item = reasonMap[reason]
    const bList = item.list || []
    let iInfo = {
      upCount: 0,
      downCount: 0,
      upSum: 0,
      downSum: 0,
      sum: 0,
      len: bList.length
    }
    let rInfo = {
      upCount: 0,
      downCount: 0,
      upSum: 0,
      downSum: 0,
      sum: 0,
      len: bList.length
    }
    bList.forEach((v) => {
      iInfo.sum += v.showIncome
      if (v.showIncome > 0) {
        iInfo.upCount++
        iInfo.upSum += v.showIncome
      } else {
        iInfo.downCount++
        iInfo.downSum += v.showIncome
      }
      if (v.incomeRate > 0) {
        rInfo.upCount++
        rInfo.upSum += v.incomeRate
      } else {
        rInfo.downCount++
        rInfo.downSum += v.incomeRate
      }
    })
    result[reason] = {
      type: item.type,
      iInfo,
      rInfo
    }
  }
  return result
}

exports.getRecentQuoteVolume = async (time) => {
  const list = await QuoteVolume.find({}, {
    skip: 0,
    limit: 2,
    sort: '-time'
  })
  if (list[0] && list[0].time === time) {
    // 已经有了
    return {
      now: list[0],
      last: list[1]
    }
  }
  return {
    now: null,
    last: list[0]
  }
}

exports.addQuoteVolumeRecord = async (time, data) => {
  const info = await this.getRecentQuoteVolume(time)
  const last = info.last || {}
  if (data.total_margin_balance !== undefined) {
    data.balance_change = numberUtil.keepSixDecimals(data.total_margin_balance - (last.total_margin_balance || 0) || 0)
  }
  if (info.now) {
    await QuoteVolume.update({
      time: time
    }, {
      ...data
    })
  } else {
    await QuoteVolume.newAndSave({
      time: time,
      ...data
    })
  }
}

// 统计做空做多盈亏情况
exports.getTradeStatisticsByDirection = async function (query) {
  const queryNew = {
    market: 2, // 只统计合约交易
    type: { $in: ['sell', 'buy'] } // 只统计开仓操作，不包含平仓
  }

  // 时间范围过滤
  if (query.startTime || query.endTime) {
    queryNew.create_at = {}
  }
  if (query.startTime) {
    queryNew.create_at.$gte = new Date(query.startTime)
  }
  if (query.endTime) {
    queryNew.create_at.$lte = new Date(query.endTime)
  }

  // 根据方向过滤：1-只统计做多，2-只统计做空
  if (query.direction) {
    if (query.direction === '1') {
      queryNew.type = 'buy' // 做多：买入开多
    } else if (query.direction === '2') {
      queryNew.type = 'sell' // 做空：卖出开空
    }
  }

  // 根据reason过滤，exactMatch是1就是精准匹配
  if (query.reason) {
    if (query.exactMatch === 1) {
      // 精准匹配
      queryNew.reason = query.reason
    } else {
      // 模糊匹配（以reason为开头）
      queryNew.reason = {
        $regex: `^${query.reason}`,
        $options: 'i'
      }
    }
  }

  const opt = {
    sort: '-create_at',
    lean: true
  }

  const records = await ExecuteRecord.find(queryNew, opt)

  // 初始化统计结构
  const createStatsObject = () => ({
    count: 0, // 总交易笔数
    profitCount: 0, // 盈利笔数
    lossCount: 0, // 亏损笔数
    breakEvenCount: 0, // 持平笔数
    profitAmount: 0, // 盈利总金额(USDT)
    lossAmount: 0, // 亏损总金额(USDT)
    totalAmount: 0, // 净盈亏(USDT)
    profitRate: 0, // 盈利总收益率(%)
    lossRate: 0, // 亏损总收益率(%)
    totalRate: 0, // 净收益率(%)
    profitPosition: 0, // 盈利总仓位(USDT)
    lossPosition: 0, // 亏损总仓位(USDT)
    totalPosition: 0, // 总仓位(USDT)
    maxProfit: 0, // 最大单笔盈利(USDT)
    maxLoss: 0, // 最大单笔亏损(USDT)
    maxProfitRate: 0, // 最大单笔盈利率(%)
    maxLossRate: 0, // 最大单笔亏损率(%)
    totalCommission: 0, // 总手续费(USDT)
    avgHoldDays: 0, // 平均持仓天数
    maxHoldDays: 0, // 最大持仓天数
    minHoldDays: 999999, // 最小持仓天数
    totalHoldDays: 0 // 总持仓天数
  })

  const stats = {
    long: { // 做多统计
      total: createStatsObject(),
      reasons: {},
      strategies: {} // 按策略统计
    },
    short: { // 做空统计
      total: createStatsObject(),
      reasons: {},
      strategies: {} // 按策略统计
    },
    overall: createStatsObject(), // 总体统计
    timeDistribution: { // 时间分布统计
      hourly: {}, // 按小时统计
      daily: {}, // 按日统计
      monthly: {} // 按月统计
    },
    codeStats: {} // 按交易对统计
  }

  records.forEach(record => {
    const isLong = record.type === 'buy'
    const direction = isLong ? 'long' : 'short'
    const income = record.income_result || 0
    const incomeRate = record.income_rate_result || 0
    const position = Math.abs(record.usdt || 0)
    const reason = record.reason || 'unknown'
    const strategy = record.strategy || 'unknown'
    const code = record.code || 'unknown'
    const commission = record.commission || 0
    const holdDays = record.keep_days || 0

    // 时间分布统计
    const createTime = new Date(record.create_at)
    const hour = createTime.getHours()
    const day = createTime.getDay() // 0-6, 0是周日
    const month = createTime.getMonth() + 1 // 1-12

    // 初始化各种统计对象
    // const initStats = (target) => {
    //   if (!target) return createStatsObject()
    //   return target
    // }

    if (!stats[direction].reasons[reason]) stats[direction].reasons[reason] = createStatsObject()
    if (!stats[direction].strategies[strategy]) stats[direction].strategies[strategy] = createStatsObject()
    if (!stats.codeStats[code]) stats.codeStats[code] = createStatsObject()
    if (!stats.timeDistribution.hourly[hour]) stats.timeDistribution.hourly[hour] = createStatsObject()
    if (!stats.timeDistribution.daily[day]) stats.timeDistribution.daily[day] = createStatsObject()
    if (!stats.timeDistribution.monthly[month]) stats.timeDistribution.monthly[month] = createStatsObject()

    // 更新统计数据的函数
    const updateStats = (target) => {
      target.count++
      target.totalAmount += income
      target.totalRate += incomeRate
      target.totalPosition += position
      target.totalCommission += commission
      target.totalHoldDays += holdDays

      // 更新最大最小持仓天数
      if (holdDays > target.maxHoldDays) target.maxHoldDays = holdDays
      if (holdDays < target.minHoldDays && holdDays > 0) target.minHoldDays = holdDays

      if (income > 0) {
        target.profitCount++
        target.profitAmount += income
        target.profitRate += incomeRate
        target.profitPosition += position
        if (income > target.maxProfit) target.maxProfit = income
        if (incomeRate > target.maxProfitRate) target.maxProfitRate = incomeRate
      } else if (income < 0) {
        target.lossCount++
        target.lossAmount += income
        target.lossRate += incomeRate
        target.lossPosition += position
        if (income < target.maxLoss) target.maxLoss = income
        if (incomeRate < target.maxLossRate) target.maxLossRate = incomeRate
      } else {
        target.breakEvenCount++
      }
    }

    // 更新各级别统计
    updateStats(stats[direction].total)
    updateStats(stats[direction].reasons[reason])
    updateStats(stats[direction].strategies[strategy])
    updateStats(stats.overall)
    updateStats(stats.codeStats[code])
    updateStats(stats.timeDistribution.hourly[hour])
    updateStats(stats.timeDistribution.daily[day])
    updateStats(stats.timeDistribution.monthly[month])
  })

  // 格式化数值和计算衍生指标
  const formatStats = (target) => {
    // 格式化基础数值
    target.profitAmount = numberUtil.keepTwoDecimals(target.profitAmount)
    target.lossAmount = numberUtil.keepTwoDecimals(target.lossAmount)
    target.totalAmount = numberUtil.keepTwoDecimals(target.totalAmount)
    target.profitRate = numberUtil.keepTwoDecimals(target.profitRate)
    target.lossRate = numberUtil.keepTwoDecimals(target.lossRate)
    target.totalRate = numberUtil.keepTwoDecimals(target.totalRate)
    target.profitPosition = numberUtil.keepTwoDecimals(target.profitPosition)
    target.lossPosition = numberUtil.keepTwoDecimals(target.lossPosition)
    target.totalPosition = numberUtil.keepTwoDecimals(target.totalPosition)
    target.maxProfit = numberUtil.keepTwoDecimals(target.maxProfit)
    target.maxLoss = numberUtil.keepTwoDecimals(target.maxLoss)
    target.maxProfitRate = numberUtil.keepTwoDecimals(target.maxProfitRate)
    target.maxLossRate = numberUtil.keepTwoDecimals(target.maxLossRate)
    target.totalCommission = numberUtil.keepTwoDecimals(target.totalCommission)

    // 计算衍生指标
    target.winRate = target.count > 0 ? numberUtil.keepTwoDecimals((target.profitCount / target.count) * 100) : 0 // 胜率
    target.lossRate_percent = target.count > 0 ? numberUtil.keepTwoDecimals((target.lossCount / target.count) * 100) : 0 // 败率
    target.avgProfit = target.profitCount > 0 ? numberUtil.keepTwoDecimals(target.profitAmount / target.profitCount) : 0 // 平均盈利
    target.avgLoss = target.lossCount > 0 ? numberUtil.keepTwoDecimals(Math.abs(target.lossAmount) / target.lossCount) : 0 // 平均亏损
    target.profitLossRatio = target.avgLoss !== 0 ? numberUtil.keepTwoDecimals(target.avgProfit / target.avgLoss) : 0 // 盈亏比
    target.avgPosition = target.count > 0 ? numberUtil.keepTwoDecimals(target.totalPosition / target.count) : 0 // 平均仓位
    target.avgCommission = target.count > 0 ? numberUtil.keepTwoDecimals(target.totalCommission / target.count) : 0 // 平均手续费
    target.commissionRate = target.totalPosition > 0 ? numberUtil.keepTwoDecimals((target.totalCommission / target.totalPosition) * 100) : 0 // 手续费率
    target.netProfitRate = target.totalPosition > 0 ? numberUtil.keepTwoDecimals(((target.totalAmount - target.totalCommission) / target.totalPosition) * 100) : 0 // 净收益率
    target.avgHoldDays = target.count > 0 ? numberUtil.keepTwoDecimals(target.totalHoldDays / target.count) : 0 // 平均持仓天数
    target.sharpeRatio = 0 // 夏普比率(需要更多数据计算)
    target.maxDrawdown = 0 // 最大回撤(需要按时间序列计算)

    // 处理最小持仓天数的边界情况
    if (target.minHoldDays === 999999) target.minHoldDays = 0
  }

  // 格式化所有统计数据
  formatStats(stats.overall)
  formatStats(stats.long.total)
  formatStats(stats.short.total)

  Object.values(stats.long.reasons).forEach(formatStats)
  Object.values(stats.short.reasons).forEach(formatStats)
  Object.values(stats.long.strategies).forEach(formatStats)
  Object.values(stats.short.strategies).forEach(formatStats)
  Object.values(stats.codeStats).forEach(formatStats)
  Object.values(stats.timeDistribution.hourly).forEach(formatStats)
  Object.values(stats.timeDistribution.daily).forEach(formatStats)
  Object.values(stats.timeDistribution.monthly).forEach(formatStats)

  // 转换对象统计为数组格式
  const formatObjectStats = (statsObj) => {
    return Object.keys(statsObj).map(key => ({
      key,
      ...statsObj[key]
    })).sort((a, b) => b.count - a.count)
  }

  return {
    // 数据说明
    dataDescription: {
      count: '总交易笔数',
      profitCount: '盈利笔数',
      lossCount: '亏损笔数',
      breakEvenCount: '持平笔数',
      profitAmount: '盈利总金额(USDT)',
      lossAmount: '亏损总金额(USDT)',
      totalAmount: '净盈亏(USDT)',
      profitRate: '盈利总收益率(%)',
      lossRate: '亏损总收益率(%)',
      totalRate: '净收益率(%)',
      profitPosition: '盈利总仓位(USDT)',
      lossPosition: '亏损总仓位(USDT)',
      totalPosition: '总仓位(USDT)',
      maxProfit: '最大单笔盈利(USDT)',
      maxLoss: '最大单笔亏损(USDT)',
      maxProfitRate: '最大单笔盈利率(%)',
      maxLossRate: '最大单笔亏损率(%)',
      totalCommission: '总手续费(USDT)',
      winRate: '胜率(%)',
      lossRate_percent: '败率(%)',
      avgProfit: '平均单笔盈利(USDT)',
      avgLoss: '平均单笔亏损(USDT)',
      profitLossRatio: '盈亏比(盈利/亏损)',
      avgPosition: '平均仓位(USDT)',
      avgCommission: '平均手续费(USDT)',
      commissionRate: '手续费率(%)',
      netProfitRate: '净收益率(扣除手续费,%)',
      avgHoldDays: '平均持仓天数',
      maxHoldDays: '最大持仓天数',
      minHoldDays: '最小持仓天数'
    },
    // 总体统计
    overview: stats.overall,
    // 做多统计
    long: {
      total: stats.long.total,
      reasons: formatObjectStats(stats.long.reasons),
      strategies: formatObjectStats(stats.long.strategies)
    },
    // 做空统计
    short: {
      total: stats.short.total,
      reasons: formatObjectStats(stats.short.reasons),
      strategies: formatObjectStats(stats.short.strategies)
    },
    // 按交易对统计
    // codeStats: formatObjectStats(stats.codeStats),
    // 时间分布统计
    // timeDistribution: {
    //   hourly: formatObjectStats(stats.timeDistribution.hourly), // 按小时(0-23)
    //   daily: formatObjectStats(stats.timeDistribution.daily), // 按星期(0-6,0是周日)
    //   monthly: formatObjectStats(stats.timeDistribution.monthly) // 按月份(1-12)
    // },
    // 查询信息
    queryInfo: {
      startTime: query.startTime,
      endTime: query.endTime,
      direction: query.direction,
      reason: query.reason,
      totalRecords: records.length,
      description: {
        direction: '1-只统计做多, 2-只统计做空, 空-全部方向',
        timeRange: '统计时间范围',
        reason: '特定交易原因过滤'
      }
    }
  }
}
